package ru.demo.abstarctservice.adapter.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ru.demo.abstarctservice.adapter.mapper.AbstractMapper;
import ru.demo.abstarctservice.app.api.AbstractService;
import ru.demo.abstarctservice.entity.BaseEntity;

import java.util.List;
import java.util.UUID;

@RequiredArgsConstructor
public class AbstractController<Entity extends BaseEntity, Dto> {

    protected final AbstractService<Entity> service;
    protected final AbstractMapper<Entity, Dto> mapper;

    @GetMapping
    public ResponseEntity<List<Dto>> getAll() {
        List<Entity> entities = service.getAll();
        return new ResponseEntity<>(mapper.mapListToDto(entities), HttpStatus.OK);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Dto> getById(@PathVariable UUID id) {
        Entity entity = service.getById(id);
        return new ResponseEntity<>(mapper.mapToDto(entity), HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<Dto> create(@RequestBody Dto dto) {
        Entity entity = service.create(mapper.mapFromDto(dto));
        return new ResponseEntity<>(mapper.mapToDto(entity), HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Dto> update(@PathVariable UUID id, @RequestBody Dto dto) {
        Entity entity = service.update(id, mapper.mapFromDto(dto));
        return new ResponseEntity<>(mapper.mapToDto(entity), HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable UUID id) {
        service.delete(id);
        return new ResponseEntity<>(HttpStatus.OK);
    }

}
